<template>
  <div class="map">
    <div class="map" id="map" ref="map" style="cursor: default;background-color:#fff">
      <div id="map-icons" @mouseover="mapiconMouseOver()" @mouseout="mapiconMouseOut()">
        <ul>
          <li
            v-for="(item, index) in maplist"
            :index="index"
            style="right: 0px;"
            :value="item.pkid"
            @click="chooseMap(index)"
          >
            <div>
              <img :src="item.imgUrl">
            </div>
            <span :class="item.icon">
              <div class="map-icons-font">{{item.name}}</div>
            </span>
          </li>
        </ul>
      </div>
      <div class="pointMap" v-show="module=='manager'" @click="pointInMap">点选</div>
    </div>
    <el-dialog :visible.sync="showDetail" v-if="showDetail" width="1280px" top="100px" title="项目详情">
      <detail-info :projectId="pjtId"></detail-info>
    </el-dialog>
  </div>
</template>
<script>
import L from "leaflet";
import "../../../static/libs/iclient9-leaflet.js";
import "../../../static/libs/iclient9-leaflet.css";
import "leaflet/dist/leaflet.css";
import Vue from "vue";
import detailInfo from "../manage/ProjectInfo.vue";
import { ServiceConfig, Sites, host } from "../tool/Global/app-config.js";
import {
  getMap,
  getMapById,
  queryProMonthScheduleByProjectid,
  queryProjectMediaByScheduleid,
  getArchiveFile
} from "../tool/Global/app-mgr.js";
let makerlayer = null;
let myGroup = null;
let icon = {
  defaultIcon: require("../../../static/img/icon.png")
};
let redIcon = L.icon({
  iconUrl: icon.defaultIcon,
  iconSize: [50, 50],
  iconAnchor: [26, 44]
});
var first = false;
var tooltip = L.tooltip({
  direction: "right"
});
var popupVue = Vue.extend({
  template:
    "<div class='projectInfo'><div class='title'>项目基本信息</div><div class='prjName'><span>项目名称</span>{{info.projectName}}</div><div class='prjLocation'><span>建设地址</span>{{info.build_location}}</div><div class='prjName'><span>建设内容</span>{{info.build_scale}}</div><div class='detail' @click='getDetailInfo'>查看详情</div></div>",
  data() {
    return {
      info: {}
    };
  },
  methods: {
    getDetailInfo() {}
  }
});
export default {
  props: ["lat", "lng", "module", "projectsInfo"],
  components: {
    detailInfo
  },
  data: function() {
    return {
      showDetail: false,
      archiveUrl: ServiceConfig.archiveUrl,
      pjtId: "",
      maplist: [],
      layerGroup: L.layerGroup(),
      showPopup: null,
      layer_crs_info: "",
      cur_layers: []
    };
  },
  watch: {
    lat(curVal, oldVal) {
      this.putonmap();
    },
    lng(curVal, oldVal) {
      this.putonmap();
    },
    projectsInfo: {
      handler(newValue, oldValue) {
        if (this.showPopup) {
          this.map.closePopup(this.showPopup);
        }
        this.drawProjectPoint();
      },
      deep: true
    }
  },
  mounted() {
    let ref = this;
    this.$nextTick(function() {
      ref.initMaps();
    });
  },

  methods: {
    pointInMap() {
      if (!first) {
        this.map.on("mousemove", this.pointerMoveHandler);
        this.map.on("click", this.pointerClickHandler);
        //this.map.on("click",this.clickMap());
      }
    },
    pointerMoveHandler(evt) {
      tooltip.setContent("点击选择坐标");
      tooltip.setLatLng(evt.latlng);
      tooltip.addTo(this.map);
    },
    pointerClickHandler(e) {
      if (this.map.hasLayer(makerlayer)) {
        this.map.removeLayer(makerlayer);
      }
      makerlayer = L.marker(e.latlng, { icon: redIcon }).addTo(this.map);
      this.$emit("getPoint", e.latlng);
    },
    initMaps() {
      let self = this;
      getMap().then(res => {
        let maps = res.data;
        if (maps.resultInfo.data && maps.resultInfo.data.items.length > 0) {
          let data = maps.resultInfo.data.items;
          for (var i = 0; i < data.length; i++) {
            if (data[i].realspaceurl == null) {
              var map_data = {
                pkid: data[i].pkid,
                name: data[i].name,
                index: data[i].index,
                centerX: data[i].centerX,
                centerY: data[i].centerY,
                mapType: data[i].mapType,
                layers: data[i].layers,
                initLevel: data[i].initLevel,
                versions: data[i].versions,
                isOpenHistory: data[i].openHistory,
                imgUrl: data[i].imgUrl,
                bbox: data[i].bbox,
                projection: data[i].projection,
                identifier: data[i].identifier,
                networkUrl: data[i].networkUrl,
                addressMatchingUrl: data[i].addressMatchingUrl,
                clickNum: 0 //记录该图地图切换的次数
              };
              //self.maps_data.push(map_data);
              map_data.imgUrl =
                host + Sites.appframework + "/" + data[i].imgUrl;
              +data[i].imgUrl;
              self.maplist.push(map_data);
            }
          }
          if (self.maplist.length > 0) {
            self.maplist.reverse();
            self.map = L.map("map", {
              center: [self.maplist[0].centerY, self.maplist[0].centerX],
              zoom: self.maplist[0].initLevel,
              attributionControl: false
            });
            var version =
              self.maplist[self.maplist.length - 1].layers[0].version;
            self.addLayers(self.maplist[self.maplist.length - 1], version);
          } else {
            alert("当前地图没有发布服务！");
          }
        }
      });
    },
    addLayers(mapInfo, version) {
      var ref = this;
      var mapLayers = mapInfo.layers;
      var extra = 0;
      for (var i = 0; i < mapLayers.length; i++) {
        if (
          mapLayers[i].version == version &&
          mapLayers[i].status == 1 &&
          mapLayers[i].layerType != null &&
          mapLayers[i].layerType == "SMRESTMAP"
        ) {
          var layerUrl = decodeURI(mapLayers[i].layerUrl);
          //初始化rest地图图层
          if (
            mapLayers[i].name != null &&
            mapLayers[i].name != undefined &&
            mapLayers[i].name != ""
          ) {
            if (mapLayers[i].name.indexOf("[") < 0) {
              var layerIDArray = mapLayers[i].name.split(",");
              var layerIndex = layerIDArray[0].split(":")[0];
              var layerNum = layerIDArray[0].split(":")[1];
              mapLayers[i].name = "[" + layerIndex + ":";

              for (var ii = 0; ii < layerIDArray.length; ii++) {
                if (layerIndex == layerIDArray[ii].split(":")[0]) {
                  layerNum = layerIDArray[ii].split(":")[1];
                  mapLayers[i].name = mapLayers[i].name + layerNum + ",";
                } else {
                  layerIndex = layerIDArray[ii].split(":")[0];
                  layerNum = layerIDArray[ii].split(":")[1];
                  mapLayers[i].name =
                    mapLayers[i].name + layerIndex + ":" + layerNum + ",";
                }
              }
              mapLayers[i].name = mapLayers[i].name.substring(
                0,
                mapLayers[i].name.lastIndexOf(",")
              );
              mapLayers[i].name = mapLayers[i].name + "]";
            }
          }
          if (ref.getCRS(mapInfo.projection)) {
            //天地图
            // ref.map.options.crs = new L.Proj.CRS(
            //   ref.getCRS(mapInfo.projection).code,
            //   {
            //     origin: L.point([mapLayers[i].bbox[0], mapLayers[i].bbox[3]]),
            //     bounds: L.bounds(
            //       [mapLayers[i].bbox[0], mapLayers[i].bbox[1]],
            //       [mapLayers[i].bbox[2], mapLayers[i].bbox[3]]
            //     )
            //   }
            // );
            if (!this.layer_crs_info) {
              this.layer_crs_info = new L.Proj.CRS(
                ref.getCRS(mapInfo.projection).code,
                {
                  origin: L.point([mapLayers[i].bbox[0], mapLayers[i].bbox[3]]),
                  bounds: L.bounds(
                    [mapLayers[i].bbox[0], mapLayers[i].bbox[1]],
                    [mapLayers[i].bbox[2], mapLayers[i].bbox[3]]
                  )
                }
              );
              ref.map.options.crs = this.layer_crs_info;
            }
          } else {
            ref.map.options.crs = L.CRS.NonEarthCRS({
              origin: L.point([mapLayers[i].bbox[0], mapLayers[i].bbox[3]]),
              bounds: L.bounds(
                [mapLayers[i].bbox[0], mapLayers[i].bbox[1]],
                [mapLayers[i].bbox[2], mapLayers[i].bbox[3]]
              )
            });
          }
          ref.layerGroup
            .addLayer(
              L.supermap.tiledMapLayer(layerUrl, {
                transparent: true
              })
            )
            .addTo(ref.map);
          // 因为湖南天地图原因，特别为期宁外设置了放大倍数，后续可以删除本段及参数
          if (
            layerUrl ===
            "http://222.247.40.204:8091/iserver/services/map-tdt/rest/maps/vec"
          ) {
            extra = 10;
          }
        }
        if (
          mapLayers[i].version == version &&
          mapLayers[i].status == 1 &&
          mapLayers[i].layerType != null &&
          mapLayers[i].layerType == "WMTS"
        ) {
          var name = mapLayers[i].name;
          var url = decodeURI(mapLayers[i].layerUrl);
          var matrixSet = mapLayers[i].matrixSet;
          var scale = mapLayers[i].scale;
          var maxScale = mapLayers[i].maxScale;
          var minScale = mapLayers[i].minScale;
          var startLevel = mapLayers[i].startLevel;
          var endLevel = mapLayers[i].endLevel;
          //获取瓦片类型
          var format = mapLayers[i].format ? mapLayers[i].format : "image/png";
          if (url.indexOf("tianditu") > 0) {
            format = "tiles";
          }
          var resolution = [];
          if (mapLayers[i].resolution) {
            for (var re = 0; re < mapLayers[i].resolution.length; re++) {
              resolution.push(mapLayers[i].resolution[re]);
            }
          }
          if (ref.getCRS(mapInfo.projection)) {
            if (resolution.length > 0) {
              ref.map.options.crs = new L.Proj.CRS(
                mapInfo.projection == "EPSG:4490"
                  ? "EPSG:4326"
                  : mapInfo.projection,
                {
                  origin: L.point([mapLayers[i].bbox[0], mapLayers[i].bbox[3]]),
                  resolutions: resolution,
                  bounds: L.bounds(
                    [mapLayers[i].bbox[0], mapLayers[i].bbox[1]],
                    [mapLayers[i].bbox[2], mapLayers[i].bbox[3]]
                  )
                }
              );
            } else {
              ref.map.options.crs = ref.getCRS(mapInfo.projection);
            }
          } else {
            if (resolution.length > 0) {
              ref.map.options.crs = L.CRS.NonEarthCRS({
                origin: L.point([mapLayers[i].bbox[0], mapLayers[i].bbox[3]]),
                resolutions: resolution,
                bounds: L.bounds(
                  [mapLayers[i].bbox[0], mapLayers[i].bbox[1]],
                  [mapLayers[i].bbox[2], mapLayers[i].bbox[3]]
                )
              });
            } else {
              ref.map.options.crs = L.CRS.NonEarthCRS({
                origin: L.point([mapLayers[i].bbox[0], mapLayers[i].bbox[3]]),
                bounds: L.bounds(
                  [mapLayers[i].bbox[0], mapLayers[i].bbox[1]],
                  [mapLayers[i].bbox[2], mapLayers[i].bbox[3]]
                )
              });
            }
          }

          //L.supermap.tiandituTileLayer().addTo(ref.map);
          ref.layerGroup
            .addLayer(
              L.supermap.wmtsLayer(url, {
                layer: name,
                style: "default",
                tilematrixSet: matrixSet,
                format: format
              })
            )
            .addTo(ref.map);
        }
      }
      //设置地图最大显示级别
      if (ref.map.options.crs.options) {
        ref.map.options.maxZoom =
          ref.map.options.crs.options.resolutions == undefined
            ? 18
            : ref.map.options.crs.options.resolutions.length - 1;
      } else {
        ref.map.options.maxZoom = 18;
      }
      //重新定位中心点
      var centerX = mapInfo.centerX;
      var centerY = mapInfo.centerY;
      var level = extra ? extra : mapInfo.initLevel;
      if (this.extra_level) {
        centerX = 28.19;
        centerY = 112.78;
      }
      ref.map.setView([centerY, centerX], level, true);
      if (ref.module == "manager") {
        //this.initDrawControl();
      }
      if (ref.projectsInfo) {
        ref.drawProjectPoint();
      }
      this.putonmap();
    },
    initDrawControl() {
      let ref = this;
      var drawnItems = new L.FeatureGroup();
      this.map.addLayer(drawnItems);
      var drawControl = new L.Control.Draw({
        draw: {
          polyline: false,
          polygon: false,
          circle: false,
          rectangle: false,
          marker: false
        },
        edit: {
          featureGroup: drawnItems
        }
      });
      this.map.addControl(drawControl);
      this.map.on(L.Draw.Event.CREATED, function(e) {
        drawnItems.clearLayers();
        let type = e.layerType;
        let layer = e.layer;
        var selectPoint = e.layer._latlng;
        drawnItems.addLayer(layer);
        ref.$emit("getPoint", selectPoint);
      });
    },
    getCRS(crsCode) {
      var crs;
      if (crsCode.indexOf("EPSG:4326") > -1) {
        return L.CRS.EPSG4326;
      } else if (crsCode.indexOf("EPSG:3857") > -1) {
        return L.CRS.EPSG3857;
      } else if (crsCode.indexOf("EPSG:4490") > -1) {
        return L.CRS.TianDiTu_WGS84;
      } else if (crsCode.indexOf("EPSG:900913") > -1) {
        return L.CRS.TianDiTu_Mercator;
      } else {
        return false;
      }
    },

    putonmap() {
      if (this.map) {
        if (this.map.hasLayer(makerlayer)) {
          this.map.removeLayer(makerlayer);
        }
        if (this.lat && this.lng) {
          makerlayer = L.marker([this.lat, this.lng], { icon: redIcon }).addTo(
            this.map
          );
        }
      }
    },
    drawProjectPoint() {
      if (this.map) {
        let ref = this;
        var i;
        var layers = [];
        if (myGroup) {
          myGroup.clearLayers();
        }
        var minY = 0;
        var minX = 0;
        var maxY = 0;
        var maxX = 0;
        var boolean = true;
        for (i = 0; i < ref.projectsInfo.length; i++) {
          var projectInfo = ref.projectsInfo[i];
          if (projectInfo.consLocationSmx && projectInfo.consLocationSmy) {
            if (boolean) {
              minY = maxY = projectInfo.consLocationSmy;
              minX = maxX = projectInfo.consLocationSmx;
              boolean = false;
            }
            var layer = L.marker(
              [projectInfo.consLocationSmy, projectInfo.consLocationSmx],
              { icon: redIcon }
            ).addTo(ref.map);
            layers.push(layer);
            ref.markerClick(layer, projectInfo);
            if (projectInfo.consLocationSmy > maxY) {
              maxY = projectInfo.consLocationSmy;
            }
            if (projectInfo.consLocationSmx > maxX) {
              maxX = projectInfo.consLocationSmx;
            }
            if (projectInfo.consLocationSmy < minY) {
              minY = projectInfo.consLocationSmy;
            }
            if (projectInfo.consLocationSmx < minX) {
              minX = projectInfo.consLocationSmx;
            }
          }
        }
        if (maxY && maxX && minX && minY) {
          var center = L.latLng(
            (maxY - minY) / 2 + minY,
            (maxX - minX) / 2 + minX
          );
          ref.map.setView(center);
        }
        if (layers.length) {
          myGroup = L.layerGroup(layers);
          ref.map.addLayer(myGroup);
        }
      }
    },
    markerClick(layer, info) {
      let ref = this;
      layer.on("click", function(e) {
        ref.pjtId = info.pkid;
        var mypop = L.popup();
        var pop = new popupVue();
        //layer.bindPopup("<div id='popup'></div>").openPopup(layer.getLatLng());
        mypop
          .setLatLng(layer.getLatLng())
          .setContent("<div id='popup'></div>")
          .openOn(ref.map);
        ref.showPopup = mypop;
        pop.$mount("#popup");
        pop.info = info;
        pop.getDetailInfo = function() {
          ref.showDetail = true;
        };
      });
    },
    mapiconMouseOver() {
      let iconlist = document.getElementById("map-icons").children[0].children;
      for (let i = 0; i < iconlist.length; i++) {
        let iconhtml = iconlist[i];
        var rightPX =
          (iconlist.length - iconhtml.getAttribute("index") - 1) * 66 + "px";
        iconhtml.style.right = rightPX;
      }
    },
    mapiconMouseOut() {
      let iconlist = document.getElementById("map-icons").children[0].children;
      for (let i = 0; i < iconlist.length; i++) {
        let iconhtml = iconlist[i];
        iconhtml.style.right = 0;
      }
    },
    chooseMap(t) {
      // zw
      this.layer_crs_info = "";
      // zw
      // try {
      //   for (const item of this.cur_layers) {
      //     item.remove();
      //   }
      //   this.cur_layers = [];
      // } catch (err) {}
      let mapclick = this.maplist[t];
      this.maplist.splice(t, 1);
      this.maplist.push(mapclick);
      this.layerGroup.clearLayers();
      var version = this.maplist[this.maplist.length - 1].layers[0].version;
      this.addLayers(this.maplist[this.maplist.length - 1], version);
    }
  }
};
</script>
<style>
.map {
  height: 100%;
  background-color: #fff;
}
.projectInfo .title {
  font-size: 20px;
  color: black;
  font-weight: 700;
}
.prjName,
.prjLocation,
.prjName {
  font-size: 15px;
  margin-top: 10px;
}
.prjName span,
.prjLocation span,
.prjName span {
  margin-right: 10px;
  color: #aac6ee;
}
.detail {
  cursor: pointer;
  margin-top: 20px;
  margin-bottom: 15px;
  color: green;
}
#popup {
  width: 400px;
}
#map-icons {
  width: 60px;
  height: 60px;
  position: absolute;
  right: 30px;
  bottom: 50px;
  z-index: 990;
}
#map-icons li {
  list-style-type: none;
  width: 60px;
  height: 60px;
  position: absolute;
  text-align: center;
  font-size: 12px;
  color: white;
  border: 2px #b3d6f1 solid;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  transition: 1s;
  -moz-transition: 1s; /* Firefox 4 */
  -webkit-transition: 1s; /* Safari 和 Chrome */
  -o-transition: 1s; /* Opera */
}
.map-icons-font {
  background: #178af5;
  opacity: 0.8;
  width: 56px;
  margin-top: 15px;
  padding: 2px;
  position: absolute;
  bottom: 10px;
}
.pointMap {
  position: absolute;
  width: 30px;
  height: 30px;
  z-index: 999;
  top: 78px;
  background-color: white;
  text-align: center;
  line-height: 30px;
  left: 12px;
  border: 1px solid #9e9e9e;
  cursor: pointer;
  box-shadow: 1px 0px 9px #9e9e9e;
}
</style>



